package com.xxx.control.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.gg.reader.api.dal.GClient;
import com.gg.reader.api.dal.HandlerGpiOver;
import com.gg.reader.api.dal.HandlerGpiStart;
import com.gg.reader.api.dal.HandlerTagEpcLog;
import com.gg.reader.api.dal.HandlerTagEpcOver;
import com.gg.reader.api.protocol.gx.LogAppGpiOver;
import com.gg.reader.api.protocol.gx.LogAppGpiStart;
import com.gg.reader.api.protocol.gx.LogBaseEpcInfo;
import com.gg.reader.api.protocol.gx.LogBaseEpcOver;
import com.xxx.control.application.App;
import com.xxx.control.base.BaseVMActivity;
import com.xxx.control.base.NoViewModel;
import com.xxx.control.bean.TagInfo;
import com.xxx.control.constant.Constant;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @author fuyujie
 * @package: com.easy.eg
 * @fileNmae BasePortActivity
 * @date 2018/6/27 17:34
 * @describe
 * @org easylinking
 * @email f279259625@gmail.com
 */

public abstract class RFIDReadActivity<vb extends ViewBinding, vm extends NoViewModel> extends BaseVMActivity<vb, vm> {

    protected App mApplication;
    // protected boolean isFirstConnrct = true;

    // public GClient client = GlobalClient.getClient();

    // private boolean isClient;
    private Map<String, TagInfo> tagInfoMap = new LinkedHashMap<String, TagInfo>();//去重数据源
    private List<TagInfo> tagInfoList = new ArrayList<TagInfo>();//适配器所需数据源
    private Long index = 1l;//索引

    private void DisplayError(String resourceId,String name) {
        LogUtils.e("读写器连接错误：" + resourceId);
        onConnectError(name);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (App) getApplication();
    }

    protected void startGetWork(GClient cgGClient) {//重新开始连接
        connect(cgGClient);
    }


    protected void connect(GClient cgGClient) {
        //isFirstConnrct = true;
        String readerIp = "";
        if( "readerA" == cgGClient.getSerialNumber()){
             readerIp = SPUtils.getInstance().getString(Constant.READER_IP, "");
        }else if("readerB" == cgGClient.getSerialNumber()){
             readerIp = SPUtils.getInstance().getString(Constant.READER_SECOND_IP, "");
        }else{
            LogUtils.e("*** 没有可连接的读写器");
        }

       // String path = SPUtils.getInstance().getString(Constant.SERIAL_PORT, "/dev/ttyS0");//串口路径

        int baudrate = 115200;

//        if (StringUtil.isEmpty(path) || baudrate == -1) {
//            return;
//        }

//        String param = path + ":" + baudrate;
//        LogUtils.e("****" + param);
        boolean success = false;
        if (!StringUtils.isTrimEmpty(readerIp)) {
            success = cgGClient.openTcp(readerIp, 1000);
        }
        if (success) {
            onConnectSuccessed();
//            LogUtils.file("isConnect 读卡器连接成功");
            LogUtils.e("*** isConnect 连接成功");

            // 事件绑定
            subHandler(cgGClient);
        } else {
            LogUtils.e("*** isConnect 连接失败");
//            LogUtils.file("isConnect 读卡器连接失败");
            DisplayError("连接失败",cgGClient.getName());
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    protected void onRestart() {
        super.onRestart();
    }

    public Map<String, TagInfo> pooled6cData(LogBaseEpcInfo info) {
        if (tagInfoMap.containsKey(info.getTid() + info.getEpc())) {
            TagInfo tagInfo = tagInfoMap.get(info.getTid() + info.getEpc());
            Long count = tagInfoMap.get(info.getTid() + info.getEpc()).getCount();
            count++;
            tagInfo.setRssi(info.getRssi() + "");
            tagInfo.setCount(count);
            tagInfoMap.put(info.getTid() + info.getEpc(), tagInfo);
        } else {
            TagInfo tag = new TagInfo();
            tag.setIndex(index);
            tag.setType("6C");
            tag.setEpc(info.getEpc());
            tag.setCount(1l);
            tag.setTid(info.getTid());
            tag.setRssi(info.getRssi() + "");
            tagInfoMap.put(info.getTid() + info.getEpc(), tag);
            index++;
        }

        return tagInfoMap;
    }

    static long inTime = 0;//进触发时间
    static long outTime = 0;//出触发时间
    static long inTime2 = 0;//进触发时间
    static long outTime2 = 0;//出触发时间
    public static long gpiInterval = 2000;//ms gpi触发进/出的间隔时间
    public static long bookReadInterval = 2000;//ms 图书读取显示间隔时间
    public static int inCount = 0;//进计数
    public static int accumulateinCount = 0; // 累计进出数
    //public static int outCount = 0;//出计数
    public int inOrOut = 0;////1进0出
    /**
     * gpi 1-0 是不是进
     */
    public boolean isGPI1IsIn = false;

    /**
     * gpi 3-2 是不是进
     */
    public boolean isGPI3IsIn = false;

    //订阅
    public void subHandler(GClient client) {
        client.onTagEpcLog = new HandlerTagEpcLog() {
            @Override
            public void log(String readerName, final LogBaseEpcInfo info) {
                if (null != info && 0 == info.getResult()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            LogUtils.file("***logAppEpcLog" + info.getEpc() + "," + info.getAntId());
                            LogUtils.e("***logAppEpcLog" + info.getEpc() + "," + info.getAntId());

                            Map<String, TagInfo> infoMap = pooled6cData(info);
                            tagInfoList.clear();
                            tagInfoList.addAll(infoMap.values());
                            onTagReceived(client.getSerialNumber(),tagInfoMap.get(info.getTid() + info.getEpc()));
                        }
                    });
                }
            }
        };
        client.onTagEpcOver = new HandlerTagEpcOver() {
            @Override
            public void log(String readerName, LogBaseEpcOver info) {
                LogUtils.e("***logAppEpcOver");
                handlerStop.sendEmptyMessage(1);
            }
        };
        client.onGpiOver = new HandlerGpiOver() {
            @Override
            public void log(String s, LogAppGpiOver logAppGpiOver) {
//                toast("***logAppGpiOver" + logAppGpiOver);
                LogUtils.e("***logAppGpiOver" + logAppGpiOver);
            }
        };
        client.onGpiStart = new HandlerGpiStart() {
            @Override
            public void log(String s, final LogAppGpiStart logAppGpiStart) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LogUtils.e("***logAppGpiStart" + logAppGpiStart.toString());
                        // 索引从0开始
                        if (null != logAppGpiStart) {
                            //可自行切换任意配置好的gpi触发索引   0-1为进  1-0为出
                            if (logAppGpiStart.getGpiPort() == (isGPI1IsIn ? 1 : 0)) {
                                inTime = TimeUtils.getNowMills();
//                                inTime = logAppGpiStart.getSystemTime().getTime();
//                        LogUtils.e("***inTime" + inTime);
                                // 出
                                if (outTime != 0) {
                                    if (inTime - outTime <= gpiInterval) {
                                        inOrOut = 0;
                                        //outCount++;
                                        onGpiStart(0);
                                        //LogUtils.e("***logApp---------出--" + outCount + "---------");
//                                        System.out.println("---------出--"+outCount+"---------");
                                        inTime = 0;
                                        outTime = 0;
                                    }
                                }
                            }

                            if (logAppGpiStart.getGpiPort() == (isGPI1IsIn ? 0 : 1)) {
                                outTime = TimeUtils.getNowMills();
//                                outTime = logAppGpiStart.getSystemTime().getTime();
                                // 进
//                        LogUtils.e("***outTime" + outTime);
                                if (inTime != 0) {
                                    if (outTime - inTime <= gpiInterval) {
                                        inOrOut = 1;
                                        inCount++;
                                        accumulateinCount++;
                                        onGpiStart(1);
                                        LogUtils.e("***logApp---------进--" + inCount + "---------");
//                                        System.out.println("---------进--"+inCount+"---------");
                                        inTime = 0;
                                        outTime = 0;
                                    }
                                }
                            }

                            //可自行切换任意配置好的gpi触发索引   2-3为进  3-2为出
                            if (logAppGpiStart.getGpiPort() == (isGPI3IsIn ? 3 : 2)) {
                                inTime2 = TimeUtils.getNowMills();
//                                inTime2 = logAppGpiStart.getSystemTime().getTime();
                                // 出
                                if (outTime2 != 0) {
                                    if (inTime2 - outTime2 <= gpiInterval) {
                                        inOrOut = 0;
                                        //outCount++;
                                        onGpiStart(0);
                                        //LogUtils.e("***logApp---------出--" + outCount + "---------");
//                                        System.out.println("---------出--"+outCount+"---------");
                                        inTime2 = 0;
                                        outTime2 = 0;
                                    }
                                }
                            }

                            if (logAppGpiStart.getGpiPort() == (isGPI3IsIn ? 2 : 3)) {
                                outTime2 = TimeUtils.getNowMills();
//                                outTime2 = logAppGpiStart.getSystemTime().getTime();
                                // 进
                                if (inTime2 != 0) {
                                    if (outTime2 - inTime2 <= gpiInterval) {
                                        inOrOut = 1;
                                        inCount++;
                                        accumulateinCount++;
                                        onGpiStart(1);
                                        LogUtils.e("***logApp---------进--" + inCount + "---------");
//                                        System.out.println("---------进--"+inCount+"---------");
                                        inTime2 = 0;
                                        outTime2 = 0;
                                    }
                                }
                            }
                        }
                    }
                });
//                toast("***logAppGpiStart" + logAppGpiStart);
            }
        };
    }


    final Handler handlerStop = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
//                    mHandler.removeCallbacks(r);
//                    List<TagInfo> tagInfos = new ArrayList<>();
//                    tagInfos.addAll(tagInfoList);
//                    onDataReceived(tagInfos);
                    clearTagInfo();
//                    isReader = false;
                    break;
            }
            super.handleMessage(msg);
        }
    };

    protected abstract void onTagReceived(String name,TagInfo tagInfo);

    protected abstract void onDataReceived(List<TagInfo> tagInfoList);

    protected abstract void onConnectError(String name);

    protected abstract void onConnectSuccessed();

    protected abstract void onGpiStart(int alarm); //alarm  1进 0出



    @Override
    protected void onDestroy() {
//        if (client != null) {
//            LogUtils.e("isConnect onDestroy========" + "client.close");
//            client.close();
////            client = null;
//        }
//        if (cgGClient != null) {
//            LogUtils.e("isConnect onDestroy========" + "client.close");
//            cgGClient.close();
////            client = null;
//        }
        super.onDestroy();
    }

    public void clearTagInfo() {
        tagInfoMap.clear();
        tagInfoList.clear();
    }

}
